<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watchEffect } from "vue";
import * as echarts from "echarts";

const chartRef = ref(null);
let myChart = null;

// ---------------------- 基础配置与数据（无修改） ----------------------
const weekdays = ["周一", "周二", "周三", "周四", "周五"];
const crossDayRange = "8月10日 12:00 - 8月12日 12:00";
const crossDayTotalHours = 48;

const rawData = ref([
  [48, 10.1, 11, 9, 8],
  [0, 8.9, 7, 10, 12],
  [0, 12, 13, 11, 10],
  [0, 8.3, 9, 10, 9],
  [0, 8.7, 8, 8, 9],
]);

const statusData = ref([
  ["通行", "不通行", "不通行", "通行", "通行"],
  ["", "通行", "通行", "不通行", "通行"],
  ["", "通行", "不通行", "通行", "不通行"],
  ["", "不通行", "通行", "不通行", "通行"],
  ["", "不通行", "通行", "通行", "不通行"],
]);

const statusColors = {
  通行: "#4CAF50",
  不通行: "#F44336",
};

// ---------------------- 核心方法（关键修改） ----------------------
const balanceDailyData = () => {
  weekdays.forEach((_, dayIndex) => {
    const currentSum = rawData.value.reduce(
      (sum, category) => sum + category[dayIndex],
      0
    );
    if (Math.abs(currentSum - crossDayTotalHours) > 0.01) {
      rawData.value[rawData.value.length - 1][dayIndex] +=
        crossDayTotalHours - currentSum;
    }
  });
};

/**
 * 关键修改1：删除 series.emphasis 配置（关闭hover高亮）
 * 同时删除 label 中无用的 formatter、color、fontSize（仅保留 show: false）
 */
const buildSeries = () => {
  return rawData.value.map((data, seriesIndex) => ({
    name: `系列${seriesIndex + 1}`,
    type: "bar",
    stack: "total",
    barWidth: "60%",
    label: {
      show: false, // 仅保留关闭内部文本的配置，其他无用属性删除
    },
    data: data.map((value, dataIndex) => ({
      value,
      itemStyle: {
        color: statusColors[statusData.value[seriesIndex][dataIndex]],
      },
    })),
    // 关键：删除 emphasis 配置（或注释掉），彻底关闭hover高亮效果
    // emphasis: {
    //   focus: "series", // 原hover高亮配置，删除后无高亮
    // },
  }));
};

/**
 * 关键修改2：删除 tooltip 配置（关闭鼠标移入提示框）
 * 其他配置（网格、标题、图例、坐标轴）保持不变
 */
const buildChartOption = () => {
  return {
    grid: {
      left: "20%",
      right: "8%",
      top: "18%",
      bottom: "15%",
      containLabel: true,
    },
    title: {
      text: `时间范围：${crossDayRange}（共${crossDayTotalHours}小时）`,
      left: "center",
      top: 0,
      textStyle: {
        fontSize: 14,
        color: "#333",
        fontWeight: "normal",
      },
    },
    legend: {
      data: [
        { name: "通行", icon: "rect", itemStyle: { color: statusColors.通行 } },
        {
          name: "不通行",
          icon: "rect",
          itemStyle: { color: statusColors.不通行 },
        },
      ],
      top: 30,
      left: "center",
      selectedMode: false, // 图例仅展示，不允许点击选择
      textStyle: { fontSize: 12, color: "#666" },
      itemWidth: 10,
      itemHeight: 10,
    },
    // 关键：删除 tooltip 配置（或注释掉），鼠标移入无任何提示
    // tooltip: { ... }, // 原提示框配置，删除后无交互提示
    xAxis: {
      type: "category",
      data: weekdays,
      axisLabel: { fontSize: 14, color: "#333", interval: 0 },
      axisLine: { lineStyle: { color: "#eee" } },
      name: "星期",
      nameTextStyle: { fontSize: 13, color: "#666", padding: [10, 0, 0, 0] },
      nameLocation: "middle",
      nameGap: 30,
    },
    yAxis: {
      type: "value",
      min: 0,
      max: crossDayTotalHours,
      interval: 12,
      axisLabel: {
        formatter: (value) => {
          const startDate = new Date("2023-08-10T12:00:00");
          const currentDate = new Date(startDate.getTime() + value * 3600000);
          const month = String(currentDate.getMonth() + 1).padStart(2, "0");
          const day = String(currentDate.getDate()).padStart(2, "0");
          const hours = String(currentDate.getHours()).padStart(2, "0");
          const minutes = String(currentDate.getMinutes()).padStart(2, "0");
          return `${month}-${day} ${hours}:${minutes}`;
        },
        fontSize: 11,
        color: "#666",
        align: "right",
        padding: [0, 10, 0, 0],
      },
      axisLine: { show: false },
      splitLine: { lineStyle: { color: "#f5f5f5" } },
      name: "时间",
      nameTextStyle: { fontSize: 13, color: "#666" },
      nameLocation: "middle",
      nameGap: 110,
    },
    series: buildSeries(),
    animation: true,
    animationDuration: 1000,
    animationEasing: "cubicOut",
  };
};

// ---------------------- 初始化/销毁/resize（无修改） ----------------------
const initChart = () => {
  if (!chartRef.value || myChart) return;
  myChart = echarts.init(chartRef.value);
  balanceDailyData();
  myChart.setOption(buildChartOption());
  window.addEventListener("resize", handleResize);
};

const destroyChart = () => {
  if (myChart) {
    window.removeEventListener("resize", handleResize);
    myChart.dispose();
    myChart = null;
  }
};

const handleResize = () => {
  myChart?.resize();
};

// ---------------------- 生命周期（无修改） ----------------------
onMounted(() => {
  initChart();
});

onUnmounted(() => {
  destroyChart();
});

watchEffect(() => {
  if (myChart) {
    balanceDailyData();
    myChart.setOption(buildChartOption());
  }
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 600px;
  margin: 0 auto;
}
</style>
